/**
 * Data model and retrieval methods for a Facebook user
 *
 * @package Torchd Framework
 * @subpackage Facebook
 * @author Jason Raede <jason@torchd.com>
 */
if(!torchd.FB) torchd.FB = {};


torchd.FB.user = function(id) {
	this.id = id;
	this.userInfo = {};
	this.friends = [];
	
	this.inMiddleOfRetrievingData = false;
	this.infoCallbacks = [];
};

/**
 * Get a specific field and do something to it with a callback. 
 *
 * Retrieve data from the Facebook API if the user's data hasn't grabbed yet.
 * Sort of a "lazy instantiation" for JavaScript. This way we don't bog down the
 * server with unnecessary calls to Facebook's crappy API.
 *
 * Note that this function doesn't just return the value because of the possibility
 * that we haven't yet retrieved the data.
 *
 * @param string field
 * @param function callback		What to do with the field data when retrieved
 */
torchd.FB.user.prototype.getInfo = function(field, callback) {
	var self = this;
	console.log(this.userInfo);
	if(this.userInfo.id) { // Retrieved the info
		if(this.userInfo[field]) {
			callback(this.userInfo[field]);
		}
		
	}
	else if(this.inMiddleOfRetrievingData) {
		// Wait til it finishes
		this.infoCallbacks.push({field:field, callback:callback});
	}
	else {
		// Get the data from the server and then execute the callback
		self.inMiddleOfRetrievingData = true;
		torchd.FB.conduit.getInfo('me', false, function(response) {
			self.inMiddleOfRetrievingData = false;
			self.userInfo = response;
			self.executeInfoCallbacks();
			callback(self.userInfo[field]);
		});
	}
};

/**
 * Returns the URL of the user's profile picture
 *
 * @param string size ->
 *		'square' :: 50x50
 *		'small'  :: 50x?
 *		'norma;' :: 100x?
 *		'large'  :: 200x?
 */
torchd.FB.user.prototype.profilePicture = function(size) {
	return torchd.FB.conduit.profilePicture(size, this.id);
	
};

/**
 * Execute any piled up getInfo calls if they were called
 * during an API request. Saves server load.
 */
torchd.FB.user.prototype.executeInfoCallbacks = function() {
	for(var i=0;i<this.infoCallbacks.length;i++) {
		this.getInfo(this.infoCallbacks[i].field, this.infoCallbacks[i].callback);
	}
	this.infoCallbacks = [];
};

/**
 * Gets an array of the user's friends
 *
 * @param function callback		The function to run upon retrieval
 */
torchd.FB.user.prototype.getFriends = function(callback) {
	var self = this;
	if(this.friends.length) {
		callback(this.friends);
	}
	else {
		torchd.FB.conduit.getInfo('me/friends', false, function(response) {
			self.friends = response.data;
			callback(self.friends);
		});
	}
};